use clickhouse_rs::types::SqlType;

use crate::base::{get_ch_pool, get_config};

pub struct TmpTable {
    pub name: String,
}
impl TmpTable {
    pub fn from(name: String) -> Self {
        TmpTable {
            name,
        }
    }
    pub fn get_name(&self) -> &str {
        self.name.as_str()
    }
    pub async fn create(&self,cols: &Vec<(String, SqlType)>) -> anyhow::Result<()> {
        let mut client = get_ch_pool().get_handle().await?;
        let db_name = get_config().clickhouse.database.as_str();
        let sql_str = format!(
            "create table if not exists {}.{} ({}) ENGINE = Memory",
            db_name,
            self.name,
            cols
                .iter()
                .map(|(name, sql_type)| format!("`{}` {}", name, sql_type))
                .collect::<Vec<_>>()
                .join(",")
        );
        client.execute(sql_str).await?;
        let sql_str=format!("truncate table {}",self.name);
        client.execute(sql_str).await?;
        Ok(())
    }
    // pub async fn clear(&self) -> anyhow::Result<()> {
    //     if !table_is_exist(&self.name).await? {
    //         return Ok(());
    //     }
    //     let mut client = get_ch_pool().get_handle().await?;
    //     let db_name = get_config().clickhouse.database.as_str();
    //     let sql_str = format!("truncate table {}.{}", db_name, self.name);
    //     client.execute(sql_str).await?;
    //     Ok(())
    // }
    // pub async fn drop(&self) -> anyhow::Result<()> {
    //     let mut client = get_ch_pool().get_handle().await?;
    //     let db_name = get_config().clickhouse.database.as_str();
    //     let sql_str = format!(
    //         "drop table if exists {}.{}",
    //         db_name,
    //         self.name
    //     );
    //     client.execute(sql_str).await?;
    //     Ok(())
    // }
}

